package erp

import (
	"context"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/product/rpc/productclient"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type InventoryChangeCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 订单发货成功回调
func NewInventoryChangeCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InventoryChangeCallbackLogic {
	return &InventoryChangeCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *InventoryChangeCallbackLogic) InventoryChangeCallback(
	req *types.InventoryChangeCallbackReq,
) (*types.ErpCallbackResp, error) {
	// logrus.Infof(fmt.Sprintf("InventoryChangeCallbackReq: %+v", req))
	// {ItemId:0xc001519130 Quantity:0xc00169d0a8 ShopNick:0xc001519150 SkuId:0xc001519140}
	logx.Infof("InventoryChangeCallback req: %+v ", req)
	if req.ItemId == nil || len(*req.ItemId) == 0 {
		logx.Errorw("InventoryChangeCallback Error: ItemId is empty")
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.Quantity == nil {
		logx.Errorw("InventoryChangeCallback Error: Quantity is empty")
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.ShopNick == nil || len(*req.ShopNick) == 0 {
		logx.Errorw("InventoryChangeCallback Error: ShopNick is empty")
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.SkuId == nil || len(*req.SkuId) == 0 {
		logx.Errorw("InventoryChangeCallback Error: SkuId is empty")
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	_, err := l.svcCtx.ProductRpc.UpdateProductStock(l.ctx, &productclient.UpdateProductStockReq{
		Data: map[string]uint64{
			*req.SkuId: *req.Quantity,
		},
	})
	if err != nil {
		logx.Errorw("InventoryChangeCallback Error:", logx.Field("detail", err.Error()))
		return nil, err
	}

	return &types.ErpCallbackResp{
		Success: true,
	}, nil
}
